import { MENU_CONFIG, START_MENU } from 'services/Config'

let ActiveMenu = START_MENU // 当前路由所在的一级菜单
let ActiveTag = '1' // 当前活动菜单 AsideDefaultActive
const Menu = {
  state: {
    CurrentMenu: START_MENU, // 当前一级菜单
    AsideDefaultActive: '1', // 当前默认活动菜单-默认首页
    AsideMenu: MENU_CONFIG.find(i => i.name === START_MENU) // 侧边栏菜单
  },
  mutations: {
    // 一级菜单选择改变
    SetCurrentMenu (state, v) {
      state.CurrentMenu = v
      state.AsideMenu = MENU_CONFIG.find(i => i.name === v)
      if (state.AsideDefaultActive === '1') return
      // 如果进入的不是路由所在菜单，记录当前AsideDefaultActive，并清空当前AsideDefaultActive值
      if (state.CurrentMenu !== ActiveMenu) {
        ActiveTag = state.AsideDefaultActive || ActiveTag
        state.AsideDefaultActive = ''
      } else {
        // 重回路由所在菜单时将AsideDefaultActive重新赋值
        state.AsideDefaultActive = state.AsideDefaultActive || ActiveTag
      }
    },
    // 路由改变导致菜单变化
    SetMenuByRouteChange (state, v) {
      if (v.routeName === 'Homepage') {
        state.AsideDefaultActive = '1'
      } else {
        // 进入的路由不是首页时，重新设置当前、活动菜单、侧边栏菜单
        MENU_CONFIG.forEach(menu => {
          menu.children.forEach((item, index) => {
            if (item.route === v.routeName) {
              state.CurrentMenu = menu.name
              ActiveMenu = menu.name
              state.AsideDefaultActive = `${index + 1}`
              state.AsideMenu = menu
            }
            item.children &&
            item.children.forEach((i, num) => {
              if (i.route === v.routeName) {
                state.CurrentMenu = menu.name
                ActiveMenu = menu.name
                state.AsideDefaultActive = `${index + 1}-${num + 1}`
                state.AsideMenu = menu
              }
            })
          })
        })
      }
    }
  }
}

export default Menu
